.TH std::basic_string::operator[] 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::basic_string::operator[] \- std::basic_string::operator[]

.SH Synopsis
   CharT& operator[]( size_type pos );             \fB(1)\fP (constexpr since C++20)
   const CharT& operator[]( size_type pos ) const; \fB(2)\fP (constexpr since C++20)

   Returns a reference to the character at specified location pos if pos < size(), or a
   reference to CharT() if pos == size(). No bounds checking is performed.

   If pos > size(), the behavior is undefined.

   For overload \fB(1)\fP, if pos == size(), the behavior is undefined
   if the object referred by the returned reference is modified to any value other than
   CharT()
   \fI(since C++11)\fP.

.SH Parameters

   pos - position of the character to return

.SH Return value

   *(begin() + pos) if pos < size(), or a reference to CharT() if pos == size().

.SH Complexity

   Constant.

.SH Example


// Run this code

 #include <iostream>
 #include <string>

 int main()
 {
     const std::string e("Exemplar");
     for (unsigned i = e.length() - 1; i != 0; i /= 2)
         std::cout << e[i];
     std::cout << '\\n';

     const char* c = &e[0];
     std::cout << c << '\\n'; // print as a C string

     // Change the last character of s into a 'y'
     std::string s("Exemplar ");
     s[s.size() - 1] = 'y'; // equivalent to s.back() = 'y';
     std::cout << s << '\\n';
 }

.SH Output:

 rmx
 Exemplar
 Exemplary

   Defect reports

   The following behavior-changing defect reports were applied retroactively to
   previously published C++ standards.

      DR    Applied to            Behavior as published              Correct behavior
   LWG 259  C++98      non-const overload could return const lvalue changed to return
                       data()[pos], which was ill-formed            *(begin() + pos)
                       if pos == size(), the behavior of modifying
   LWG 2475 C++11      the                                          well-defined if
                       object referred by the returned reference    modified to CharT()
                       was undefined

.SH See also

   at         accesses the specified character with bounds checking
              \fI(public member function)\fP
   front      accesses the first character
   (DR*)      \fI(public member function)\fP
   back       accesses the last character
   (DR*)      \fI(public member function)\fP
   operator[] accesses the specified character
              \fI(public member function of std::basic_string_view<CharT,Traits>)\fP
